
<?php

function makeDir($path) {
	return is_dir($path) or (makeDir(dirname($path)) and @mkdir($path, 0777));
}
/**
 * 判断是否是手机登陆的
 * @return boolean
 */
function isMobile() {
	$mobile = array();
	static $mobilebrowser_list ='Mobile|iPhone|Android|WAP|NetFront|JAVA|OperasMini|UCWEB|WindowssCE|Symbian|Series|webOS|SonyEricsson|Sony|BlackBerry|Cellphone|dopod|Nokia|samsung|PalmSource|Xphone|Xda|Smartphone|PIEPlus|MEIZU|MIDP|CLDC';
	//note 获取手机浏览器
	if(preg_match("/$mobilebrowser_list/i", $_SERVER['HTTP_USER_AGENT'], $mobile)) {
		return true;
	}else{
		if(preg_match('/(mozilla|chrome|safari|opera|m3gate|winwap|openwave)/i', $_SERVER['HTTP_USER_AGENT'])) {
			return false;
		}else{
			if($_GET['mobile'] === 'yes') {
				return true;
			}else{
				return false;
			}
		}
	}
}


function pwd_md5($strinf){
  return md5($strinf);
}
  //多图上传
function sendpic($img,$address){
 for($i=0;$i<count($img);$i++){
           $newImgType= substr($img[$i],0,strrpos($img[$i],';'));  //图片的类型
           $base=substr($img[$i],strrpos($img[$i],';')+1);
           $a=explode(',',$base);
           $types=explode('/',$newImgType);
           $type=$types[1];
           $filename = rand(0,100000).time().".".$type; 
           $xmlstr=base64_decode($a[1]);
           makeDir($address);
           $file = fopen($address.$filename,"w");//打开文件准备写入  
           fwrite($file,$xmlstr);//写入
           fclose($file);//关闭
           $fileaddress[]='/'.$address.$filename;
         } 
         $info=implode('|',$fileaddress);
         return $info.'|';
       }
     //单图上传
       function sendonepic($img,$address){
        $newImgType= substr($img,0,strrpos($img,';'));  //图片的类型
        $base=substr($img,strrpos($img,';')+1);
        $a=explode(',',$base);
        $types=explode('/',$newImgType);
        $type=$types[1];
        $filename = rand(0,100000).time().".".$type; 
        $xmlstr=base64_decode($a[1]);
        makeDir($address);
        $file = fopen($address.$filename,"w");//打开文件准备写入  
        fwrite($file,$xmlstr);//写入
        fclose($file);//关闭
        $fileaddress='/'.$address.$filename;
        return $fileaddress;
      }
//图片缩放
      function img_big_min($img,$sin,$w,$h,$address){
        if(!is_array($img)){
         $array_img=explode($sin,$img);
       }else{
         $array_img=$img;
       }
       foreach ($array_img as $key => $value) {
        if(empty($value)){
         unset($array_img[$key]);
       }
     }
     makeDir($address);
     foreach ($array_img as $key => $value) {
      $image = new \Think\Image(); 
      $image->open('./'.$value);
      $address_im=$address.time().rand(1000000,9999999).'.'.jpg;
      $image->thumb($w, $h)->save($address_im); 
      $array_img_min.=substr($address_im,1).'|';
    }

    return $array_img_min;
  }    

//图片缩放  一张
  function img_big_min_one($img,$sin,$w,$h,$address){
    makeDir($address);
    $image = new \Think\Image(); 
    $image->open('./'.$img);
    $address_im=$address.time().rand(1000000,9999999).'.'.jpg;
    $image->thumb($w, $h)->save($address_im); 
    $array_img_min.=substr($address_im,1);
    return $array_img_min;
  } 


//获取城市
  function more_city(){
    $domain=$_SERVER['HTTP_HOST'];
    $city=explode('.', $domain);
    $where['city_domain'] = $city['0'];
    $city_info=M('areas')->field('id,pid,area_name,level')->where($where)->find();
    if(empty($city_info)){
      $ip='peoplehub_discuss';
      $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=3j2s1pCFpoATNL5tcr014rqZbDV8EUh6&ip={$ip}&coor=bd09ll");
      $info = json_decode($content);
      $area_name=$info->{'content'}->{'address_detail'}->{'city'};
      $city_name=str_replace('市','',$area_name);
      $map['area_name'] = array('like','%'.$city_name.'%');
      $city_info=M('areas')->field('id,pid,area_name,level')->where($map)->find();
    }
    return $city_info;
  }

  function format_date($time){
    $t=time()-$time;
    $f=array(
      '31536000'=>'年',
      '2592000'=>'个月',
      '604800'=>'星期',
      '86400'=>'天',
      '3600'=>'小时',
      '60'=>'分钟',
      '1'=>'秒'
    );
    foreach ($f as $k=>$v)    {
      if (0 !=$c=floor($t/(int)$k)) {
        return $c.$v.'前';
      }
    }
  }

//手机多张图片上传
  function allImg($s_imgphoto,$address,$sign,$day){
    if(!is_array($s_imgphoto)){
     $s_imgphoto=explode("|", $s_imgphoto);
   }
   $address=ltrim($address,'/');
   foreach ($s_imgphoto as $key => $value) {
            $newImgType[$key] = substr($value,0,strrpos($value,','));  //图片的类型
            $post=strrpos($value,',')+1;
            $newImgbase64[$key] = substr($value,$post);  
            $filename = rand(0,100000).time().".".$newImgType[$key]; //图片二进制流
            $xmlstr=base64_decode($newImgbase64[$key]);
            $jpg = $xmlstr; //得到post过来的二进制原始数据
            if($day==1){
             $y=date("Y",time());
             $m=date("m",time());
             $d=date("d",time());
             $day=$y.'-'.$m.'-'.$d;
             $address=$address.$day.'/';
           }
           makeDir($address);
            $file = fopen($address.$filename,"w");//打开文件准备写入  
            $fileaddressS_imgphoto[$key]='/'.$address.$filename.'|';
            fwrite($file,$jpg);//写入
            fclose($file);//关闭
          } 
          foreach ($fileaddressS_imgphoto as $key => $value) {
          $s_imgphotoUrlAll.=$value;  //多张图片拼接成一个字符串
        }
        $s_imgphotoUrlAll=substr($s_imgphotoUrlAll, 0, -1);
        $s_imgphotoUrlAll=ltrim($s_imgphotoUrlAll,'/');
         // $_POST['s_imgphoto']=$s_imgphotoUrlAll;
        return '/'.$s_imgphotoUrlAll;
      }
      //通过地区名字 获取地区代码 地区
      function oneAddressDemeCity($aress){
        $aress=mb_substr(trim($aress), 0, 3, 'utf-8');
        if(!empty($aress)){
         $where['area_name']=array('like',$aress.'%');
         $address=M('areas')->where($where)->field('id')->find();
         return $address['id'];
       }else{
         return '';
       }
     }
      //通过代码获取 地区的名字
     function demoAddressName($id){
      $where['id']=$id;
      $info=M('areas')->where($where)->find();
      return $info['area_name'];
    }
//数组 循环去掉 empty
    function em_set($array){
      if(is_array($array)){
       if(is_null($array)){
        return $array=array();
      }else{
        foreach ($array as $key => $value) {
         if(is_null($value)){
          $array[$key]='';
        }else{
          if(is_array($value)){
           $array[$key]=em_set($value);
         }
       }
     }
   }
   return $array;
 }else{
  if(is_null($array)){
    return $array='';
  }
}
}

     //花名
function flo_name(){
  $floor_name1=M('floor_name')->where("f_type=1")->select();
  $floor_name2=M('floor_name')->where("f_type=2")->select();
  $rand1=rand(0,19);
  $rand2=rand(0,27);
  $floor_name_one=$floor_name1[$rand1]['f_name'];
  $floor_name_two=$floor_name2[$rand2]['f_name'];
  $flo_name=$floor_name_one.$floor_name_two;
  return $flo_name;
}

     //手机 一张图片上传
function oneImg($s_imghead,$address,$sign,$day){   //s_imghead 二进制流 address 位置 $sign 特殊符
  if(!is_array($s_imghead)){
   $s_imghead=explode("|", $s_imghead);
 }
 $address=ltrim($address,'/');
//处理发布详情封面图片
 foreach ($s_imghead as $key => $value) {
            $newImgType[$key] = substr($value,0,strrpos($value,','));  //图片的类型
            $post=strrpos($value,',')+1;
            $newImgbase64[$key] = substr($value,$post);  
            $filename = rand(0,100000).time().".".$newImgType[$key]; //图片二进制流
            $xmlstr=base64_decode($newImgbase64[$key]);
            $jpg = $xmlstr; //得到post过来的二进制原始数据
            if($day==1){
             $y=date("Y",time());
             $m=date("m",time());
             $d=date("d",time());
             $day=$y.'-'.$m.'-'.$d;
             $address=$address.$day.'/';
           }
           makeDir($address);
            $file = fopen($address.$filename,"w");//打开文件准备写入  
            $fileaddress[$key]=$address.$filename;
            fwrite($file,$jpg);//写入
            fclose($file);//关闭
          } 
          foreach ($fileaddress as $key => $value) {
          $s_imgheadUrlAll.=$value;  //多张图片拼接成一个字符串
        }
                // $this->ajaxRturn((object)$s_imgphotoUrlAll); exit();
         // $_POST['s_imghead']=$s_imgheadUrlAll;//封面图片
        return '/'.$s_imgheadUrlAll; //返回字符串
 //处理发布详情封面图片
      }

/**
 * 将逗号间隔数据转换为数组
 * @param unknown $str
 * @return multitype:
 */
function field2ids($str)
{
  $str = trim($str, ',');
  return explode(',', $str);
}
##模板辅助函数#####


        //curl封装
function curl($curl, $https = true, $method , $data = null)
{
        $ch = curl_init();//初始化
        curl_setopt($ch, CURLOPT_URL, $curl);//设置访问的URL
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置不需要头信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容，但不输出
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不做服务器认证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不做客户端认证
          }
          if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, true);//设置请求是POST方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置POST请求的数据
          }

        $str = curl_exec($ch);//执行访问，返回结果
        curl_close($ch);//关闭curl，释放资源
        return $str;

      }

#生成url
      function URL($params)
      {
        return U($params);
      }

#生成label
      function c_label($value = '')
      {
        return $value;
      }

#生成input %realname%,''
      function c_text($name, $value = '', $class = '', $attr = '')
      {
        return '<input type="text" id="' . $name . '" name="' . $name . '" value="' . $value . '" class="' . $class . '" ' . $attr . ' />';
      }

#生成img
      function c_img($name, $value = '', $class = '', $attr = '')
      {
        return '<img src="' . $value . '"  alt="' . $name . '" class="' . $class . '" ' . $attr . ' />';
      }

#生成textarea
      function c_textarea($name, $value = '', $class = '', $attr = '')
      {
        return '<textarea  class="' . $class . '" id="' . $name . '" name="' . $name . '" ' . $attr . '>' . $value . '</textarea>';
      }

#生成hidden
      function c_hidden($name, $value = '')
      {   if($value=='datesjc'){
        $value=time();
      }
      return '<input type="hidden"  id="' . $name . '" name="' . $name . '" value="' . $value . '" />';
    }

#生成密码域
    function c_pwd($name, $value = '', $class = '', $attr = '')
    {
      return '<input type="password" id="' . $name . '" name="' . $name . '" value="' . $value . '" class="' . $class . '" ' . $attr . ' />';
    }

#生成时间选择框
    function c_date($name, $value = '', $class = '', $attr = '')
    {
      if ($value != '' && is_numeric($value) && $value != 0) $value = date("Y-m-d", $value);
      return c_text($name, $value, $class . ' datepicker', $attr);
    }

    function c_datetime($name, $value = '', $class = '', $attr = '')
    {
      if ($value != '' && is_numeric($value) && $value != 0) $value = date("Y-m-d H:i", $value);
      return c_text($name, $value, $class . ' datetimepicker', $attr);
    }

#生成2段时间选择
    function c_date_2($v1 = '', $v2 = '',$file)
    {
      if ($v1 != '' && is_numeric($v1) && $v1 != 0) $v1 = date("Y-m-d", $v1);
      if ($v2 != '' && is_numeric($v2) && $v2 != 0) $v2 = date("Y-m-d", $v2);
      return c_date('time_start', $v1, $class, $attr) . c_date('time_end', $v2, $class, $attr).c_hidden('timequantumnorepeat',$file);
    }

#生成编辑器
    function c_editor($name, $value = '', $class = '', $attr = 'style=" width:99%;height:300px;"')
    {
      $str = c_textarea($name, $value, $class, $attr);
      $str .= '<script type="text/javascript">
      KindEditor.ready(function(K) {
       K.create("#' . $name . '", {
        themeType : "simple"
        }); 
        });         
        </script>';
        return $str;
      }

/**
 * 生成select
 * @param unknown $name select的name
 * @param unknown $all_value select的数据
 * @param string $select_value 默认选择
 * @param string $class 样式名称
 * @param string $attr 扩展属性名
 * @param string $default_value 默认值
 * @return string
 */
function c_select($name, $all_value, $select_value = '', $class = '', $attr = '', $default_value = '')
{
  $str = '<select name="' . $name . '"  id="' . $name . '" class="' . $class . '" ' . $attr . '>';
  if ($default_value != '') $str .= $default_value;
  
  if ($all_value) {
    foreach ($all_value as $k => $v) {
      if ($select_value != '' && ($k == $select_value || in_array($k, $select_value))) {
        $str .= '<option value="' . $k . '" selected="selected" >' . $v . '</option>';
      } else {
        $str .= '<option value="' . $k . '"  >' . $v . '</option>';
      }
    }
  }
  $str .= '</select>';
  return $str;
}

/**
 * 生成多选的select
 * @param unknown $name select的name
 * @param unknown $all_value select的数据
 * @param string $select_value 默认选择
 * @param string $class 样式名称
 * @param string $attr 扩展属性名
 * @param string $default_value 默认值
 * @param number $size 高度
 * @return string
 */
function c_select_muli($name, $all_value, $select_value = array(), $class = '', $attr = '', $default_value = '', $size = 10)
{
  return c_select($name, $all_value, $select_value, $class, $attr = 'multiple="multiple" size="' . $size . '"', $default_value);
}

#生成单选按钮组
function c_radio($name, $all_value, $select_value = '', $class = '', $attr = '')
{
  $str = '';
  foreach ($all_value as $k => $v) {
    $str .= '<label class="radio"><input type="radio" name="' . $name . '" value="' . $k . '" ' . (($k) == ($select_value) ? 'checked="checked"' : '') . ' class="' . $class . '" ' . $attr . ' /><span>' . $v . '</span></label>';
  }
  return $str;
}

#生成多选按钮组
function c_checkbox($name, $all_value, $select_value = '', $class = '', $attr = '')
{
  $str = '';
  if (!is_array($select_value)) $select_value = field2ids($select_value);
  if ($all_value) {
    foreach ($all_value as $k => $v) {
      $str .= '<label class="checkbox"><input name="' . $name . '" type="checkbox" value="' . $k . '" ' . ($select_value != '' && ($k == $select_value || in_array($k, $select_value) || strpos($k, $select_value) !== false) ? 'checked="checked"' : '') . ' />' . $v . '</label>';
    }
  }
  return $str;
}
// $str .= '<script type="text/javascript">
//       KindEditor.ready(function(K) {
//        K.create("#' . $name . '", {
//         themeType : "simple"
//         }); 
//         });         
//         </script>';
//         return $str;
//       }
#生成上传框
function c_upload($name, $value = '', $num = 1)
{
  $str = c_text($name, $value);
  $vv = $name . "_" . rand(100000, 999999);
  $str .= ' <input class="btn" type="button" name="uploadButton" id="' . $vv . '" value="上传" />';
  $str .= "<script>
  KindEditor.ready(function(K) {
    var editor = K.editor({
     allowFileManager : true
     });

     K('#" . $vv . "').click(function() {
       editor.loadPlugin('image', function() {
        editor.plugin.imageDialog({
         showRemote : false,
         imageUrl : K('#" . $name . "').val(),
         clickFn : function(url, title, width, height, border, align) {
          K('#" . $name . "').val(url);
          editor.hideDialog();
        }
        });
        });
        });
        });
        </script>";
        return $str;
      }

#生成上传视频框
      function c_upload_video($name, $value = '', $num = 1)
      {
        $str = c_text($name, $value);
        $vv = $name . "_" . rand(100000, 999999);
        $str .= ' <input class="btn" type="button" name="uploadButton" id="' . $vv . '" value="上传" />';
        $str .= "<script>
        KindEditor.ready(function(K) {
          var editor = K.editor({
           allowFileManager : true
           });

           K('#" . $vv . "').click(function() {
             editor.loadPlugin('media', function() {
              editor.plugin.media.edit({
               clickFn : function(url,title) {
                K('#" . $name . "').val(url);
                editor.hideDialog();
              }
              });
              });
              });
              });
              </script>";
              return $str;
            }

#生成多图上传框
            function c_uploads($name, $value = '', $num = 1)
            {
              $vv = $name . "_" . rand(100000, 999999);
              $vs = explode("\r\n", trim($value));
              $str .= '<ul id="' . $vv . '_show" class="upload-img-list">';
              foreach ($vs as $s) {
                if ($s != '') $str .= '<li><img src="' . $s . '" /><i>X</i></li>';
              }
              $str .= '</ul>';
              $str .= ' <input class="btn-imgs" type="button" name="uploadButton" id="' . $vv . '" value="+" />';
              $str .= c_textarea($name, $value, 'hide');
              $str .= "<script>
              KindEditor.ready(function(K) {
                var editor = K.editor({
                 allowFileManager : true
                 });

                 K('#" . $vv . "').click(function() {
                  editor.loadPlugin('multiimage', function() {
                    editor.plugin.multiImageDialog({
                     clickFn : function(urlList) {
                      var img = K('#" . $name . "');
                      var div = K('#" . $vv . "_show');
                      var str = '';
                      K.each(urlList, function(i, data) {
                       str += data.url + \"\\r\\n\";
                       div.append('<li><img src=\"' + data.url + '\"><i>X</i></li>');
                       });
                       img.html(img.html() + \"\\r\\n\" + str);
                       editor.hideDialog();
                     }
                     });
                     });
                     });
                     });

                     $().ready(function(e) {
                      $('#" . $vv . "_show li i').click(function(){
                       i = ($('#" . $vv . "_show li').index($(this).parent()));
                       $(this).parent().remove();
                       tmp = $('#" . $name . "').html();
                       arr = tmp.split('\\n');
                       tmp2 = '';
                       for(j=0; j<arr.length; j++) {
                        if (j!=i) tmp2 += arr[j] + '\\r\\n';
                      }
                      $('#" . $name . "').html(tmp2);
                      })
                      }); 

                      </script>";
                      return $str;
                    }

                    function f_upload($name, $v, $w = 150, $h = 30, $txt = '点击上传', $class = '', $callback = '')
                    {
                      $timestamp = time();
                      $obj_name = $name . "_input_" . rand(10000, 99999);
                      $str = "<input id='" . $obj_name . "' class='" . $class . "' name='" . $name . "' type='file' multiple='true' style=' display:none;'>
                      " . c_hidden($name, $v) . "
                      <script type='text/javascript'>
                      setTimeout(function(){  
                        $(function() {
                         $('#" . $obj_name . "').uploadify({
                          'formData'     : {
                           'timestamp' : '" . $timestamp . "',
                           'token'     : '" . md5('unique_salt' . $timestamp) . "'
                           },
                           'buttonClass'  :'" . $class . "',
                           'buttonImage'   : null,    
                           'width'      : '" . $w . "',
                           'height'   : '" . $h . "',
                           'buttonText' : '" . $txt . "',
                           'swf'          : '/Public/uploadify/uploadify.swf?v=" . rand(100000, 999999) . "',
                           'uploader'     : '" . URL("Helper/upload") . "',
                           'fileObjName'  : 'file',
                           'fileTypeDesc'  : '请选择图片，仅支持格式JPG,BMP,PNG,GIF，最大4M',
                           'fileTypeExts'  : '*.JPG;*.GIF;*.PNG;*.BMP;',
                           'queueID'    : '',
                           'onUploadSuccess': function(file,data,response) {
                             if(response==true){
                              if(data.indexOf('#Err')==-1){
                                $('#" . $obj_name . "').append('<img src=\"'+data+'\" />');
                                upload_callback('" . $name . "',data);
                                " . ($callback != '' ? str_replace("_NAME_", $name, str_replace("_DATA_", 'data', $callback)) : '') . "
                                }else{
                                 data=eval('('+data+')');
                                 alert(data.msg);
                               }
                               }else{
                                alert('上传失败');
                              }
                              },
                              'onUploadError': function(file,data,response) {
                               alert('上传失败');
                             }    
                             });
                             });
                             " . ($v == '' ? '' : "$().ready(function(e) { $('#" . $obj_name . "').append('<img src=\"" . $v . "\" />'); });") . "
                             }," . rand(1, 5) . ");   
                             </script>";
                             return $str;
                           }

#生成提交按钮
                           function c_btn($type = "submit", $name = "提交", $click = '', $class = 'btn btn-success')
                           {
                            return '<button type="' . $type . '" name="submit" value="submit" onclick="' . $click . '" class="' . $class . '">' . $name . '</button>';
                          }

#模板内辅助table显示函数
                          function get_name($id, $from)
                          {

                            
                            if (strpos($from, '_key') > 0) {
                              $from = substr($from, 0, -4);
                            }
                            return $GLOBALS[$from][$id];
                          }

                          function get_state_name($id)
                          {
                            if ($id == 1)
                              return '进行时';
                            if ($id == 2)
                              return '已完成';
                          }

                          function get_push_type($id)
                          {
                            return $GLOBALS['push_type'][$id];
                          }

                          function get_position($id)
                          {
                            return $GLOBALS['position'][$id];
                          }

                          function get_child_contrast_physical_version1($id)
                          {
                            return $GLOBALS['child_contrast_physical_version1'][$id];
                          }

                          function get_child_contrast_physical_version2($id)
                          {
                            return $GLOBALS['child_contrast_physical_version2'][$id];
                          }

                          function get_child_contrast_physical1($id)
                          {
                            return $GLOBALS['child_contrast_physical1'][$id];
                          }

                          function get_child_contrast_physical2($id)
                          {
                            return $GLOBALS['child_contrast_physical2'][$id];
                          }


#模板内辅助table显示函数 checkbox
                          function get_field_name($id)
                          {
                            $fields = explode(',', $id);

                            $str = '';
                            foreach ($fields as $val) {
                              $str .= $GLOBALS['field_id'][$val] . ' | ';
                            }

                            return trim($str, ' | ');
                          }

# 验证码
                          function verify()
                          {
                            $config = array('fontSize' => 16,
                              'length' => 4,
                              'useNoise' => false,
                              'useCurve' => false,
                              'fontttf' => '4.ttf',
                              'imageW' => 110,
                              'imageH' => 34,
                            );
                            $Verify = new \Think\Verify($config);
                            $Verify->entry();
                          }

                          function get_mod($id, $field, $mod)
                          {
                            if (!$id) return;
                            return D($mod)->where("id={$id}")->getField($field);
                          }

                          function get_role_mod($id, $field, $mod)
                          {
                            if (!$id) return;
                            return D($mod)->where("role_id={$id}")->getField($field);
                          }

                          function get_mods($ids, $field, $mod, $sp = ',')
                          {
                            if (!$ids) return;
                            $ary_ids = field2ids($ids);
                            if ($ary_ids == '') return '';
                            $res = array();
                            foreach ($ary_ids as $id) {
                              $res[] = D($mod)->where("id={$id}")->getField($field);
                            }
                            return implode($sp, $res);
                          }


                          function get_field($mod, $field, $id)
                          {
                            $M = D($mod)->find($id);
                            if ($M) {
                              return $M[$field];
                            } else {
                              return '-';
                            }
                          }

                          function get_user($id, $format = "[email]")
                          {
                            $M = D('User')->find($id);
                            if ($M) {
                              foreach ($M as $k => $v) {
                                $format = str_replace("[$k]", $v, $format);
                              }
                              return $format;
                            } else {
                              return '-';
                            }
                          }

                          function get_company($id, $format = "[name]")
                          {
                            $M = D('Company')->find($id);
                            if ($M) {
                              foreach ($M as $k => $v) {
                                $format = str_replace("[$k]", $v, $format);
                              }
                              return $format;
                            } else {
                              return '-';
                            }
                          }

                          function get_designer($id, $format = "[name]")
                          {
                            $M = D('Designer')->find($id);
                            if ($M) {
                              foreach ($M as $k => $v) {
                                $format = str_replace("[$k]", $v, $format);
                              }
                              return $format;
                            } else {
                              return '-';
                            }
                          }


                          function get_pay_info($pay_log_id)
                          {
                            $pay_log = D('PayLog')->find($pay_log_id);
    //$ticket_order = D('TicketOrder')->where("pay_log_id=$pay_log_id")->find();
                            if (!$pay_log) return '不存在的支付单';
                            return get_mod($pay_log['payment_id'], 'name', 'Payment') . ' / ' . ($pay_log['pay_time'] > 0 ? date("Y-m-d H:i:s", $pay_log['pay_time']) : '<font color="red">订单未支付</font>');
                          }

#
                          function get_yn($id)
                          {
                            return $GLOBALS['yn'][$id];
                          }


                          function get_ad_type($id)
                          {
                            return $GLOBALS['ad_type'][$id];
                          }

#显示图片
                          function show_pic($img)
                          {
                            return "<img src='{$img}' border='0' class='l-img' />";
                          }

#获得时间
                          function get_datetime($time)
                          {
                            if ($time == 0) {
                              return '-';
                            } else {
                              return date("Y-m-d H:i:s", $time);
                            }
                          }

#获得日期
                          function get_date($time)
                          {
                            if ($time == 0) {
                              return '-';
                            } else {
                              return date("Y-m-d", $time);
                            }
                          }

                          function get_page_param($ary)
                          {
                            $ret = array();
                            foreach ($ary AS $k => $v) {
                              $ret[$k] = trim($v[1], '%');
                            }
                            $post = $_POST;
                            $get = $_GET;
                            $request = array_merge($get, $post, $ret);
                            unset($request['m'], $request['c'], $request['a'], $request['submit']);
    #var_dump($request);
                            return $request;
                          }

                          function urlencode_res($value)
                          {
                            if (empty($value)) {
                              return $value;
                            } else {
                              return is_array($value) ? array_map('urlencode_res', $value) : ($value);
                            }
                          }
                          function get_img_url($img_url,$hostUrl)
                          {   

                            $str = '<a href="' . initAvatar($img_url,$hostUrl) . '" target="_blank"><img style="width:180px;height:90px;"  src="' . initAvatar($img_url,$hostUrl) . '" /></a>';
                            return $str;
                          }
/**
 * 返回正确头像
 * @param $avatar
 * @return string
 */
function initAvatar($img_url,$hostUrl)
{   
  $hostUrlInfo=$hostUrl?$hostUrl:C('MEDIA_URL');
  $imgarray=explode('|',$img_url);
  $avatar=$imgarray[0];
  if ($avatar == '' || $avatar == null) {
    return '';
  } else {
    return substr($avatar, 0, 4) == 'http' ? $avatar : 'http://'.$hostUrlInfo . $avatar;
  }
}
#生成地址下拉选择菜单
function f_area($step, $pid = 0, $cid = 0, $did = 0, $sid = 0)
{
  $province = array();
  $city = array();
  $district = array();
  $street = array();
  $js = "<script type='text/javascript'> $().ready(function(e) {";
  $str = '';
  $province = rs2select(D('CommArea')->where('pid=0')->order('ord DESC,name ASC')->select());

  $js .= "loadArea('province_id',0,'" . intval($pid) . "');";
  if ($pid > 0) {
    $city = rs2select(D('CommArea')->where("pid={$pid}")->order('ord DESC,name ASC')->select());
    $js .= "loadArea('city_id',{$pid},{$cid});";
  } else {
    $city = rs2select(D('CommArea')->where("pid=" . (int)key($province))->order('ord DESC,name ASC')->select());
    $js .= "loadArea('city_id','" . (int)key($province) . "',0);";
  }
  if ($cid > 0) {
    $district = rs2select(D('CommArea')->where("pid={$cid}")->order('ord DESC,name ASC')->select());
    $js .= "loadArea('district_id','{$cid}',{$did});";
  } else {
    $district = rs2select(D('CommArea')->where("pid=" . (int)key($city))->order('ord DESC,name ASC')->select());
    $js .= "loadArea('district_id','" . (int)key($city) . "',0);";
  }
  if ($did > 0) {
    $street = rs2select(D('CommArea')->where("pid={$did}")->order('ord DESC,name ASC')->select());
    $js .= "loadArea('street_id','{$did}',{$sid});";
  } else {
    $street = rs2select(D('CommArea')->where("pid=" . (int)key($district))->order('ord DESC,name ASC')->select());
    $js .= "loadArea('street_id','" . (int)key($district) . "',0);";
  }

  $js .= "}); </script>";

  $str .= c_select('province_id', $province, $pid);
  if ($step > 1) $str .= c_select('city_id', $city, $cid);
  if ($step > 2) $str .= c_select('district_id', $district, $did);
  if ($step > 3) $str .= c_select('street_id', $street, $sid);
  $str .= $js;
  return $str;
}
#####数据处理辅助函数#####
/**
 * 将结果集转化为kv数组
 * @param array $data 通过select获得的关联数组
 * @param string $k 返回数组key对应的data列名
 * @param string $v 返回数组valuye对应的data列名
 * @return array
 */
function rs2select($data, $k = 'id', $v = 'name')
{
  $ret = array();
  foreach ($data as $d) {
    $ret[$d[$k]] = $d[$v];
  }
  return $ret;
}

/* 验证码校验 */
function check_verify($code, $id = '')
{
 $verify = new \Think\Verify();
 $res = $verify->check($code, $id);
 return $res;
}

function Monitor($url){
 $where['url']=$url;
 $where['ctime']=date('Y-m-d H:i:s',time());
 M('monitor_url')->add($where);
}
function EchoData($datainfo,$status=1,$code=100,$info='成功',$deletedata=1){
  if($deletedata==1){
   $data['data']=$datainfo;     
 }      
 $data['info']=$info;
 $data['code']=$code;
 if($status==1){
   $data['status']='success';
 }else{
        $data['code']=($code==100)?101:$code; //如果第二个参数为0时 默认是 "101"
        $data['info']=($info=='成功')?'失败':$info; //第二个参数为0时 默认"失败"
        $data['status']='fail';
      }
      echo json_encode(em_set($data));
      exit();
    }
    //$datainfo data数据
    //$status 1成功（默认）  1失败
    //$code 状态码 100成功（默认） 其他自定义
    //$info 汉字说明
    //$deletedata 1去掉data返回参数 0不返回
    function ArrayData($datainfo,$status=1,$code=100,$info='成功',$deletedata=1){
      if($deletedata==1){
       $data['data']=$datainfo;     
     }      
     $data['info']=$info;
     $data['code']=$code;
     if($status==1){
       $data['status']='success';
     }else{
        $data['code']=($code==100)?101:$code; //如果第二个参数为0时 默认是 "101"
        $data['info']=($info=='成功')?'失败':$info; //第二个参数为0时 默认"失败"
        $data['status']='fail';
      }
      return $data;
      exit();
    }    
    
    /*提取数据表的id对应的name值 用来select*/
    function dbidname($db,$id='id',$name='name',$where,$level='',$level_jibie='2'){
      $list=  D($db)->where($where)->select();
      if (is_null($list)) {
        return array();
      } else {
        $new_list = array();
        foreach ($list as $treat) {
          $levelNum='';
          //查看是否有等级区分
          if($level){
              for($i=0;$i<$treat[$level];$i++){
                $levelNum.='---';
              }
              //有等级区分并且还有 等级显示限制
            if($level&&$level_jibie){
                         if($treat[$level]<$level_jibie){
                            $new_list[$treat[$id]] = $levelNum.$treat[$name];
                         } 
              //有等级区分并且 没有等级限制
            }  else{
                          $new_list[$treat[$id]] = $levelNum.$treat[$name]; 
            }
         //如果没有等级区分
          }else{
                          $new_list[$treat[$id]] = $levelNum.$treat[$name];
          }

        }

        return $new_list;
      }
    }


   /*
   * 生成随机字符串
   * @param int $length 生成随机字符串的长度
   * @param string $char 组成随机字符串的字符串
   * @return string $string 生成的随机字符串
   */
   function str_rand($length = 32, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    if(!is_int($length) || $length < 0) {
     return false;
   }

   $string = '';
   for($i = $length; $i > 0; $i--) {
     $string .= $char[mt_rand(0, strlen($char) - 1)];
   }

   return $string;
 }
  // 生成token
 function creatToken(){
   return md5(str_rand(32));
 }

 //创建默认名字
 function defaultName(){
  $floor_name1=M('defaultName')->where("f_type=1")->select();
  $floor_name2=M('defaultName')->where("f_type=2")->select();
  $rand1=rand(0,(count($floor_name1)-1));
  $rand2=rand(0,(count($floor_name2)-1));
  $floor_name_one=$floor_name1[$rand1]['f_name'];
  $floor_name_two=$floor_name2[$rand2]['f_name'];
  return $floor_name_one.$floor_name_two;
}

//find
function fd($db,$where,$field,$order){
 $field=$field?$field:'*';
 return  D($db)->where($where)->field($field)->order($order)->find();
}
//select
function st($db,$where,$field,$order,$page=1,$num=10){
  $field=$field?$field:'*';
  $page=$page-1;
  return D($db)->where($where)->field($field)->order($order)->limit($page*$num,$num)->select();
}    
//save
function se($db,$where,$save){
 $info=D($db)->where($where)->save($save);
 if($info!=='false'){
  return 1;
}else{
  return 0;
}
}
//add
function ad($db,$where){
 return D($db)->add($where);
}   
//delete
function dt($db,$where){
  return D($db)->where($where)->delete();
}
//获取图片字符串第一个
function getFirstExplode($picstring){
  $info= explode('|', $picstring);
  return $info[0];
}
//设置url 如果不是http 需要加上网站域名
function setUrl($url){
 $seturl=substr($url,0,4);
 if($seturl!='http'){
  return C('MEDIA_URL').$url;
}else{
  return $url;
}
}
function get_custom_btn($id) {
  $value['id'] = $id ;
  $txt = '<div class="btn-group" ><a class="btn btn-mini btn-success" href="'.U(MODULE_NAME.'/'.CONTROLLER_NAME.'/edit?id='.$value['id']).'">编辑</a>';
  $txt.= '<a class="btn btn-mini js-confirm" href="'.U(MODULE_NAME.'/'.CONTROLLER_NAME.'/del?id='.$value['id']).'">删除</a>';
  $txt.= '</div>';
  return $txt;
}

     /**
 *
 * 中英混合的字符串截取
 * @param unknown_type $sourcestr
 * @param unknown_type $cutlength
 */
     function assoc_substr($sourcestr, $cutlength,$lv) {
      $returnstr = '';
      $i = 0;
      $n = 0;
    $str_length = strlen ( $sourcestr ); //字符串的字节数
    while ( ($n < $cutlength) and ($i <= $str_length) ) {
      $temp_str = substr ( $sourcestr, $i, 1 );
        $ascnum = Ord ( $temp_str ); //得到字符串中第$i位字符的ascii码
        if ($ascnum >= 224) {//如果ASCII位高与224，
            $returnstr = $returnstr . substr ( $sourcestr, $i, 3 ); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i = $i + 3; //实际Byte计为3
            $n ++; //字串长度计1
        } elseif ($ascnum >= 192){ //如果ASCII位高与192，
            $returnstr = $returnstr . substr ( $sourcestr, $i, 2 ); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i = $i + 2; //实际Byte计为2
            $n ++; //字串长度计1
        } elseif ($ascnum >= 65 && $ascnum <= 90) {//如果是大写字母，
          $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
            $i = $i + 1; //实际的Byte数仍计1个
            $n ++; //但考虑整体美观，大写字母计成一个高位字符
          }elseif ($ascnum >= 97 && $ascnum <= 122) {
            $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
            $i = $i + 1; //实际的Byte数仍计1个
            $n ++; //但考虑整体美观，大写字母计成一个高位字符
        } else {//其他情况下，半角标点符号，
          $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
          $i = $i + 1;
          $n = $n + 0.5;
        }
      }
      if($lv){
        if($cutlength and ($cutlength*2 < $str_length) ){
          $lv_string='...';
        }
      }
      return $returnstr.$lv_string;
    }
function levelStrin($sting){

   return $sting;
}
function levelString($title,$level){
   $sting='';
   for ($i=0; $i <$level ; $i++) { 
     $sting.='---';
   }
   return $sting.$title;
}

